<?php

class Zend_View_Helper_IsAllow extends Zend_View_Helper_Abstract{

    public function isAllow( $resource=null, $idrole=null, $name="Default" ){
        
        $acl = Zend_Registry::get("acl");
        
        /* Rebuild resource */
        if(!$resource) {
            $request = Zend_Controller_Front::getInstance()->getRequest();
            $resource = array(
                'controller' => $request->getControllerName(),
                'action' => $request->getActionName() 
            );
        }
        
        $model = new Application_Model_DbTable_NghiepVu();
		$where = $model->select()->where("controller_name=?",$resource['controller'])
                                 ->where("action_name=?",$resource['action']);
        $nghiepvu = $model->fetchRow($where);
        if(!$nghiepvu){
            $nghiepvu = $model->createRow(array(
                'TenNghiepVu' => $name,
                'controller_name' => $resource['controller'],
                'action_name' => $resource['action']
            ));
            $nghiepvu->save();
        }       
        /* Rebuild role */
		$auth = Zend_Auth::getInstance();
        if(!$auth->hasIdentity()){
            $idrole = GUEST_ID;
        }elseif( !$idrole ){
            $identity = Zend_Auth::getInstance()->getIdentity();
            $idrole = $identity->MaNhom;
        }
        
        $_resource = new Zend_Acl_Resource( $nghiepvu->MaNghiepVu );
        $_role = new Zend_Acl_Role( $idrole );
        /* not set role or notexist resource in alc*/
        if(!$acl->hasRole( $_role ) || !$acl->has($_resource)){
            return false;
        }        
        
        return $acl->isAllowed($_role,$_resource);
    }
}
?>